<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <base href="<%=request.getContextPath()%>/">
  <!-- import CSS -->
  <link rel="stylesheet" type="text/css" href="static/css/vue-index.css"/>
  <style>
    /* 基础样式 */
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      overflow: hidden;
    }

    /* 主容器布局 */
    .order-container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      overflow: hidden;
    }

    /* 搜索区域 */
    .search-area {
      padding: 15px 10px 5px 10px;/*上右下左*/
      background-color: #fff;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
      flex-shrink: 0;
    }

    /* 功能按钮区域 */
    .function-area {
      padding: 5px;
      background-color: #fff;
      flex-shrink: 0;
    }

    /* 表格区域 - 占用剩余所有空间并允许内部滚动 */
    .table-area {
      flex: 1;
      overflow: hidden;
      position: relative;
      padding: 0 0;/*上下 左右*/
    }

    /* 分页区域 */
    .pagination-area {
      padding: 15px 0;
      background-color: #fff;
      box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      flex-shrink: 0;
      border-top: 1px solid #f0f0f0;
    }

    /* 操作链接 */
    .operation-links {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .text-link {
      text-decoration: none;
      cursor: pointer;
      font-size: 14px;
    }

    .text-link.primary {
      color: #409EFF;
    }

    .text-link.danger {
      color: #F56C6C;
    }

    .text-link:hover {
      opacity: 0.8;
    }

    .divider {
      margin: 0 8px;
      color: #DCDFE6;
    }

    /* 订单项和发货单样式 */
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      margin-top: 20px;
    }

    .order-total {
      margin-top: 15px;
      text-align: right;
      font-size: 16px;
    }

    .total-amount {
      font-weight: bold;
      color: #F56C6C;
      font-size: 18px;
    }

    .shipment-info {
      margin-bottom: 20px;
    }

    .shipment-details-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
    }

    .shipment-details-table th,
    .shipment-details-table td {
      border: 1px solid #EBEEF5;
      padding: 10px;
      text-align: center;
    }

    .shipment-details-table th {
      background-color: #F5F7FA;
      color: #606266;
    }
  </style>
</head>
<body>
<div id="app" class="order-container">
  <!--搜索区域-->
  <div class="search-area">
    <el-input v-model="searchForm.orderNo" style="width: 15%" size="small" placeholder="订单编号"></el-input>
    <el-select v-model="searchForm.status" placeholder="订单状态" clearable style="width: 12%; margin-left: 10px"
               size="small">
      <el-option label="待确认" :value="0"></el-option>
      <el-option label="已确认" :value="1"></el-option>
      <el-option label="已发货" :value="2"></el-option>
      <el-option label="已完成" :value="3"></el-option>
    </el-select>
    <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期"
                    size="small" style="width: 260px; margin-left: 10px">
    </el-date-picker>
    <el-button style="margin: 0 5px 0 5px" type="primary" size="small" @click="search">查询</el-button>
    <el-button style="margin: 0 5px 0 5px" type="primary" size="small" @click="reset">重置</el-button>
  </div>

  <!--功能按钮区域-->
  <div class="function-area">
    <el-button size="small" @click="add">新增订单</el-button>
    <el-button size="small" @click="simulateAppOrder">模拟APP下单</el-button>
  </div>

  <!--表格区域-->
  <div class="table-area">
    <el-table :data="tableData" ref="orderTable" style="width: 100%;" height="100%"
              @row-click="handleRowClick" :cell-style="cellStyle" :header-cell-style="headerCellStyle">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column prop="orderNo" label="订单编号"></el-table-column>
      <el-table-column prop="customerName" label="客户名称"></el-table-column>
      <el-table-column prop="totalAmount" label="订单金额">
        <template #default="scope">
          {{ formatCurrency(scope.row.totalAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{getStatusText(scope.row.status)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="240">
        <template #default="scope">
          <div class="operation-links">
            <a href="javascript:;" class="text-link primary" @click="handleView(scope.row)">查看</a>
            <span class="divider">|</span>
            <a href="javascript:;" class="text-link primary" @click="handleConfirm(scope.row)"
               v-if="scope.row.status === 0">确认订单</a>
            <a href="javascript:;" class="text-link primary" @click="handleShipment(scope.row)"
               v-if="scope.row.status === 1">生成发货单</a>
            <span class="divider">|</span>
            <a href="javascript:;" class="text-link primary" @click="handleConfirmShipment(scope.row)"
               v-if="scope.row.status === 1 && hasShipment(scope.row.id)">确认发货</a>
            <span class="divider" v-if="scope.row.status < 2">|</span>
            <el-popconfirm title="确定删除该订单吗？" @confirm="handleDelete(scope.row.id)"
                           v-if="scope.row.status < 2">
              <template #reference>
                <a href="javascript:;" class="text-link danger">删除</a>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--分页-->
  <div class="pagination-area">
    <el-pagination
            :current-page.sync="searchForm.pageNum"
            :page-size.sync="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
    </el-pagination>
  </div>

  <!--订单表单对话框-->
  <el-dialog :visible.sync="orderDialogVisible"
             :title="dialogType === 'add' ? '新增订单' : '查看订单详情'"
             width="70%">
    <!-- 订单基本信息表单 -->
    <el-form :model="orderForm" :rules="orderRules" ref="orderForm" label-width="100px"
             :disabled="dialogType === 'view'">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="orderForm.customerName" placeholder="请输入客户名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="收货地址" prop="shippingAddress">
            <el-input v-model="orderForm.shippingAddress" placeholder="请输入收货地址"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="orderForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 订单商品列表 -->
    <div class="order-items-section">
      <div class="section-header">
        <h3>订单商品</h3>
        <el-button size="small" type="primary" @click="addOrderItem" v-if="dialogType === 'add'">
          添加商品
        </el-button>
      </div>

      <el-table :data="orderForm.orderItems" border style="width: 100%">
        <el-table-column label="商品名称" prop="productName">
          <template #default="scope">
            <el-input v-model="scope.row.productName" size="small" placeholder="商品名称"
                      :disabled="dialogType === 'view'"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.productPrice" size="small" :precision="2" :min="0"
                             :disabled="dialogType === 'view'"
                             @change="calculateItemTotal(scope.$index)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" size="small" :min="1"
                             :disabled="dialogType === 'view'"
                             @change="calculateItemTotal(scope.$index)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="小计" width="150">
          <template #default="scope">
            <span>{{ formatCurrency(scope.row.totalPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" v-if="dialogType === 'add'">
          <template #default="scope">
            <el-button type="text" size="small" @click="removeOrderItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 订单总计 -->
      <div class="order-total">
        <span>订单总计: </span>
        <span class="total-amount">{{ formatCurrency(calculateOrderTotal()) }}</span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="orderDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveOrder" v-if="dialogType === 'add'" size="small">提交订单</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 生成发货单对话框 -->
  <el-dialog :visible.sync="shipmentDialogVisible"
             title="生成发货单"
             width="70%">
    <el-form :model="shipmentForm" :rules="shipmentRules" ref="shipmentForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="shipmentForm.orderNo" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="shipmentForm.customerName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="收货地址" prop="shippingAddress">
            <el-input v-model="shipmentForm.shippingAddress" placeholder="请输入收货地址"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="shipmentForm.contactName" placeholder="请输入联系人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="shipmentForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 发货商品列表 -->
    <div class="shipment-items-section">
      <div class="section-header">
        <h3>发货商品</h3>
      </div>

      <el-table :data="shipmentForm.items" border style="width: 100%">
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <el-table-column label="订购数量" prop="orderQuantity" width="100"></el-table-column>
        <el-table-column label="发货数量" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" size="small" :min="1"
                             :max="scope.row.orderQuantity"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="仓库" width="180">
          <template #default="scope">
            <el-select v-model="scope.row.warehouseId" placeholder="选择仓库" size="small">
              <el-option label="主仓库" :value="1"></el-option>
              <el-option label="南京仓库" :value="2"></el-option>
              <el-option label="上海仓库" :value="3"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="shipmentDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveShipment" size="small">生成发货单</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 确认发货对话框 -->
  <el-dialog :visible.sync="confirmShipmentDialogVisible"
             title="确认发货"
             width="50%">
    <div class="shipment-confirm">
      <div class="shipment-info">
        <h4>发货单信息</h4>
        <p><strong>发货单号：</strong>{{currentShipment.shipmentNo}}</p>
        <p><strong>订单编号：</strong>{{currentOrder.orderNo}}</p>
        <p><strong>收货地址：</strong>{{currentShipment.shippingAddress}}</p>
        <p><strong>联系人：</strong>{{currentShipment.contactName}}</p>
        <p><strong>联系电话：</strong>{{currentShipment.contactPhone}}</p>
      </div>

      <!-- 使用doT模板渲染发货明细 -->
      <div class="shipment-items">
        <h4>发货明细</h4>
        <div id="shipmentItemsContainer"></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="confirmShipmentDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmShipment" size="small">确认发货</el-button>
      </div>
    </template>
  </el-dialog>
</div>
</body>
<script src="static/js/owner/axios.min.js"></script>
<script src="static/js/owner/doT.min.js"></script>
<script src="static/js/owner/vue.js"></script>
<script src="static/js/owner/vue-index.js"></script>
<script>
  // doT模板定义 - 用于发货明细
  var shipmentItemsTmpl = doT.template(
          '<table class="shipment-details-table">' +
          '<thead>' +
          '<tr>' +
          '<th>商品名称</th>' +
          '<th>发货数量</th>' +
          '<th>仓库</th>' +
          '</tr>' +
          '</thead>' +
          '<tbody>' +
          '{{~it.shipmentItems :item:index}}' +
          '<tr>' +
          '<td>{{=item.productName}}</td>' +
          '<td>{{=item.quantity}}</td>' +
          '<td>{{=item.warehouseName}}</td>' +
          '</tr>' +
          '{{~}}' +
          '</tbody>' +
          '</table>'
  );

  // doT模板 - 用于订单详情
  var orderDetailTmpl = doT.template(
          '<div class="order-detail">' +
          '<h4>订单基本信息</h4>' +
          '<p><strong>订单编号：</strong>{{=it.orderNo}}</p>' +
          '<p><strong>客户名称：</strong>{{=it.customerName}}</p>' +
          '<p><strong>联系电话：</strong>{{=it.contactPhone}}</p>' +
          '<p><strong>收货地址：</strong>{{=it.shippingAddress}}</p>' +
          '<p><strong>订单状态：</strong>{{=it.statusText}}</p>' +
          '<p><strong>创建时间：</strong>{{=it.createTime}}</p>' +
          '<h4>订单商品</h4>' +
          '<table class="shipment-details-table">' +
          '<thead>' +
          '<tr>' +
          '<th>商品名称</th>' +
          '<th>单价</th>' +
          '<th>数量</th>' +
          '<th>小计</th>' +
          '</tr>' +
          '</thead>' +
          '<tbody>' +
          '{{~it.orderItems :item:index}}' +
          '<tr>' +
          '<td>{{=item.productName}}</td>' +
          '<td>¥{{=item.productPrice.toFixed(2)}}</td>' +
          '<td>{{=item.quantity}}</td>' +
          '<td>¥{{=item.totalPrice.toFixed(2)}}</td>' +
          '</tr>' +
          '{{~}}' +
          '</tbody>' +
          '<tfoot>' +
          '<tr>' +
          '<td colspan="3" style="text-align: right;"><strong>订单总计：</strong></td>' +
          '<td><strong>¥{{=it.totalAmount.toFixed(2)}}</strong></td>' +
          '</tr>' +
          '</tfoot>' +
          '</table>' +
          '</div>'
  );

  // Vue实例
  new Vue({
    el: '#app',
    data: function() {
      return {
        tableData: [], // 订单表格数据
        total: 0,
        searchForm: {
          pageNum: 1,
          pageSize: 10,
          orderNo: '',
          status: '',
          dateRange: []
        },
        orderDialogVisible: false,
        dialogType: 'add', // add, view
        orderForm: {
          customerName: '',
          contactPhone: '',
          shippingAddress: '',
          remark: '',
          orderItems: []
        },
        orderRules: {
          customerName: [
            { required: true, message: '请输入客户名称', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
          ],
          shippingAddress: [
            { required: true, message: '请输入收货地址', trigger: 'blur' }
          ]
        },
        shipmentDialogVisible: false,
        shipmentForm: {
          orderId: '',
          orderNo: '',
          customerName: '',
          shippingAddress: '',
          contactName: '',
          contactPhone: '',
          items: []
        },
        shipmentRules: {
          shippingAddress: [
            { required: true, message: '请输入收货地址', trigger: 'blur' }
          ],
          contactName: [
            { required: true, message: '请输入联系人', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
          ]
        },
        confirmShipmentDialogVisible: false,
        currentOrder: {},
        currentShipment: {},
        shipmentMap: {} // 存储订单ID与发货单的映射关系
      };
    },
    methods: {
      // 获取订单列表
      getOrderList() {
        // 处理日期范围
        let params = {...this.searchForm};
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0];
          params.endDate = this.searchForm.dateRange[1];
          delete params.dateRange;
        }

        axios.get('order/list', {params: params}).then(res => {
          if (res.data.code === 200) {
            this.tableData = res.data.extend.pageInfo.list;
            this.total = res.data.extend.pageInfo.total;
          } else {
            this.$message.error('获取订单列表失败');
          }
        }).catch(err => {
          this.$message.error('获取订单列表失败: ' + err.message);
        });
      },

      // 搜索
      search() {
        this.searchForm.pageNum = 1;
        this.getOrderList();
      },

      // 重置
      reset() {
        this.searchForm = {
          pageNum: 1,
          pageSize: 10,
          orderNo: '',
          status: '',
          dateRange: []
        };
        this.getOrderList();
      },

      // 新增订单
      add() {
        this.dialogType = 'add';
        this.orderDialogVisible = true;
        this.orderForm = {
          customerName: '',
          contactPhone: '',
          shippingAddress: '',
          remark: '',
          orderItems: []
        };

        if (this.$refs.orderForm) {
          this.$refs.orderForm.resetFields();
        }
      },

      // 添加订单项
      addOrderItem() {
        this.orderForm.orderItems.push({
          productId: null,
          productName: '',
          productPrice: 0,
          quantity: 1,
          totalPrice: 0
        });
      },

      // 移除订单项
      removeOrderItem(index) {
        this.orderForm.orderItems.splice(index, 1);
        this.calculateOrderTotal();
      },

      // 计算订单项总价
      calculateItemTotal(index) {
        const item = this.orderForm.orderItems[index];
        item.totalPrice = item.productPrice * item.quantity;
        return item.totalPrice;
      },

      // 计算订单总价
      calculateOrderTotal() {
        return this.orderForm.orderItems.reduce((sum, item) => {
          return sum + (item.totalPrice || 0);
        }, 0);
      },

      // 保存订单
      saveOrder() {
        this.$refs.orderForm.validate(valid => {
          if (valid) {
            if (this.orderForm.orderItems.length === 0) {
              this.$message.warning('请至少添加一件商品');
              return;
            }

            // 校验每个商品项是否都填写完整
            for (let i = 0; i < this.orderForm.orderItems.length; i++) {
              const item = this.orderForm.orderItems[i];
              if (!item.productName) {
                this.$message.warning(`第 ${i + 1} 件商品的名称不能为空`);
                return;
              }
            }

            axios.post('order/add', this.orderForm).then(res => {
              if (res.data.code === 200) {
                this.$message.success('订单提交成功');
                this.orderDialogVisible = false;
                this.getOrderList();
              } else {
                this.$message.error(res.data.msg || '提交失败');
              }
            }).catch(err => {
              this.$message.error('提交失败: ' + err.message);
            });
          }
        });
      },

      // 查看订单
      handleView(row) {
        this.dialogType = 'view';
        this.orderDialogVisible = true;
        this.currentOrder = row;

        axios.get('order/detail/' + row.id).then(res => {
          if (res.data.code === 200) {
            this.orderForm = res.data.extend.order;

            // 使用doT模板渲染订单详情
            let orderData = {...res.data.extend.order};
            orderData.statusText = this.getStatusText(orderData.status);
            setTimeout(() => {
              // 在实际项目中可以在合适的位置添加这个元素
              // document.getElementById('orderDetailContainer').innerHTML = orderDetailTmpl(orderData);
            }, 100);
          } else {
            this.$message.error(res.data.msg || '获取订单详情失败');
          }
        }).catch(err => {
          this.$message.error('获取订单详情失败: ' + err.message);
        });
      },

      // 确认订单
      handleConfirm(row) {
        this.$confirm('确认该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.put('order/confirm/' + row.id).then(res => {
            if (res.data.code === 200) {
              row.status = 1; // 更新状态为已确认
              this.$message.success('订单确认成功');
            } else {
              this.$message.error(res.data.msg || '确认订单失败');
            }
          }).catch(err => {
            this.$message.error('确认订单失败: ' + err.message);
          });
        }).catch(() => {});
      },

      // 生成发货单
      handleShipment(row) {
        this.shipmentDialogVisible = true;
        this.currentOrder = row;

        axios.get('order/detail/' + row.id).then(res => {
          if (res.data.code === 200) {
            let order = res.data.extend.order;
            this.shipmentForm = {
              orderId: order.id,
              orderNo: order.orderNo,
              customerName: order.customerName,
              shippingAddress: order.shippingAddress,
              contactName: order.customerName,
              contactPhone: order.contactPhone,
              items: []
            };

            // 初始化发货单明细
            if (order.orderItems && order.orderItems.length > 0) {
              order.orderItems.forEach(item => {
                this.shipmentForm.items.push({
                  orderItemId: item.id,
                  productId: item.productId,
                  productName: item.productName,
                  orderQuantity: item.quantity,
                  quantity: item.quantity,
                  warehouseId: 1, // 默认主仓库
                  warehouseName: '主仓库'
                });
              });
            }
          } else {
            this.$message.error(res.data.msg || '获取订单详情失败');
          }
        }).catch(err => {
          this.$message.error('获取订单详情失败: ' + err.message);
        });
      },

      // 保存发货单
      saveShipment() {
        this.$refs.shipmentForm.validate(valid => {
          if (valid) {
            // 设置仓库名称
            this.shipmentForm.items.forEach(item => {
              item.warehouseName = this.getWarehouseName(item.warehouseId);
            });

            // 创建发货单数据
            let shipmentData = {
              orderId: this.shipmentForm.orderId,
              shippingAddress: this.shipmentForm.shippingAddress,
              contactName: this.shipmentForm.contactName,
              contactPhone: this.shipmentForm.contactPhone,
              shipmentItems: this.shipmentForm.items
            };

            axios.post('shipment/createFromOrder/' + this.currentOrder.id, shipmentData).then(res => {
              if (res.data.code === 200) {
                this.$message.success('发货单生成成功');
                this.shipmentDialogVisible = false;

                // 创建发货单与订单的映射关系，用于前端检查
                let shipment = {
                  id: res.data.extend.id,
                  shipmentNo: res.data.extend.shipmentNo,
                  orderId: this.currentOrder.id,
                  status: 0, // 待发货
                  shippingAddress: this.shipmentForm.shippingAddress,
                  contactName: this.shipmentForm.contactName,
                  contactPhone: this.shipmentForm.contactPhone,
                  shipmentItems: this.shipmentForm.items
                };
                this.shipmentMap[this.currentOrder.id] = shipment;
              } else {
                this.$message.error(res.data.msg || '生成发货单失败');
              }
            }).catch(err => {
              this.$message.error('生成发货单失败: ' + err.message);
            });
          }
        });
      },

      // 确认发货对话框
      handleConfirmShipment(row) {
        this.confirmShipmentDialogVisible = true;
        this.currentOrder = row;
        this.currentShipment = this.shipmentMap[row.id];

        // 也可以从后端获取发货单信息
        // axios.get('shipment/getByOrderId/' + row.id).then(res => {
        //     if (res.data.code === 200) {
        //         this.currentShipment = res.data.extend.shipment;
        //     }
        // });

        // 使用doT模板渲染发货明细
        setTimeout(() => {
          document.getElementById('shipmentItemsContainer').innerHTML = shipmentItemsTmpl(this.currentShipment);
        }, 100);
      },

      // 确认发货
      confirmShipment() {
        axios.put('shipment/confirm/' + this.currentShipment.id).then(res => {
          if (res.data.code === 200) {
            // 更新订单和发货单状态
            this.currentOrder.status = 2; // 已发货
            this.currentShipment.status = 1; // 已发货

            this.$message.success('发货成功');
            this.confirmShipmentDialogVisible = false;
          } else {
            this.$message.error(res.data.msg || '确认发货失败');
          }
        }).catch(err => {
          this.$message.error('确认发货失败: ' + err.message);
        });
      },

      // 删除订单
      handleDelete(id) {
        axios.delete('order/delete/' + id).then(res => {
          if (res.data.code === 200) {
            this.$message.success('删除成功');
            this.getOrderList();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        }).catch(err => {
          this.$message.error('删除失败: ' + err.message);
        });
      },

      // 模拟APP下单
      simulateAppOrder() {
        this.$confirm('是否模拟APP下单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          axios.post('order/appOrder').then(res => {
            if (res.data.code === 200) {
              this.$message.success('APP下单成功，订单号：' + res.data.extend.orderNo);
              this.getOrderList();
            } else {
              this.$message.error(res.data.msg || '模拟下单失败');
            }
          }).catch(err => {
            this.$message.error('模拟下单失败: ' + err.message);
          });
        }).catch(() => {});
      },

      // 判断订单是否有发货单
      hasShipment(orderId) {
        return this.shipmentMap[orderId] !== undefined;

        // 在实际项目中，可以调用后端接口查询
        // 或者在加载订单列表时就查询每个订单是否有发货单
      },

      // 格式化金额
      formatCurrency(value) {
        if (!value) return '¥0.00';
        return '¥' + parseFloat(value).toFixed(2);
      },

      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          0: '待确认',
          1: '已确认',
          2: '已发货',
          3: '已完成'
        };
        return statusMap[status] || '未知状态';
      },

      // 获取状态类型（用于el-tag的type属性）
      getStatusType(status) {
        const typeMap = {
          0: 'info',
          1: 'warning',
          2: 'primary',
          3: 'success'
        };
        return typeMap[status] || '';
      },

      // 获取仓库名称
      getWarehouseName(warehouseId) {
        const warehouseMap = {
          1: '主仓库',
          2: '南京仓库',
          3: '上海仓库'
        };
        return warehouseMap[warehouseId] || '未知仓库';
      },

      // 分页切换
      handleSizeChange(val) {
        this.searchForm.pageSize = val;
        this.getOrderList();
      },

      handleCurrentChange(val) {
        this.searchForm.pageNum = val;
        this.getOrderList();
      },

      // 表格单元格样式
      cellStyle() {
        return {
          padding: '5px 0',
        };
      },

      // 表头样式
      headerCellStyle() {
        return {
          padding: '0 0',
        };
      },

      // 行点击事件
      handleRowClick(row) {
        this.$refs.orderTable.toggleRowSelection(row);
      }
    },
    created() {
      this.getOrderList();
    }
  });
</script>
</html>
